package com.aipartner.service.impl;

import com.aipartner.common.PageResult;
import com.aipartner.entity.UserFavorite;
import com.aipartner.entity.UserTask;
import com.aipartner.entity.WalletTransaction;
import com.aipartner.mapper.UserFavoriteMapper;
import com.aipartner.service.PersonalService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Personal Service Implementation
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PersonalServiceImpl implements PersonalService {
    
    private final UserFavoriteMapper userFavoriteMapper;
    
    @Override
    public Map<String, Object> getUserStats(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取实际的收藏数量
        Long favoriteCount = userFavoriteMapper.countByUserId(userId);
        
        // Mock data for other stats - replace with actual database queries
        stats.put("totalChats", 156);
        stats.put("totalTokens", 45000);
        stats.put("favoriteCount", favoriteCount != null ? favoriteCount : 0);
        stats.put("completedTasks", 12);
        stats.put("walletBalance", new BigDecimal("98.50"));
        stats.put("vipDaysLeft", 15);
        stats.put("joinDays", 45);
        
        return stats;
    }
    
    @Override
    public PageResult<Map<String, Object>> getUserFavorites(Long userId, String contentType, Long current, Long size) {
        try {
            // 创建分页对象
            Page<UserFavorite> page = new Page<>(current, size);
            
            // 分页查询用户收藏
            IPage<UserFavorite> favoritePage = userFavoriteMapper.selectUserFavoritesPage(page, userId, contentType);
            
            // 转换为Map格式
            List<Map<String, Object>> favorites = favoritePage.getRecords().stream()
                    .map(this::convertFavoriteToMap)
                    .collect(Collectors.toList());
            
            return new PageResult<>(200, "Success", favorites, 
                                   favoritePage.getTotal(), 
                                   favoritePage.getPages(), 
                                   current == 1, 
                                   current >= favoritePage.getPages(),
                                   current.intValue(), 
                                   size.intValue());
        } catch (Exception e) {
            log.error("Error getting user favorites: userId={}", userId, e);
            return new PageResult<>(500, "Error getting favorites", new ArrayList<>(), 
                                   0L, 0L, true, true, 
                                   current.intValue(), size.intValue());
        }
    }
    
    @Override
    public boolean addToFavorites(Long userId, String contentType, String contentId, String title, String content, String imageUrl, String contentData) {
        try {
            // 检查是否已收藏
            UserFavorite existing = userFavoriteMapper.selectByUserAndContent(userId, contentType, contentId);
            if (existing != null) {
                log.warn("Content already favorited: userId={}, type={}, id={}", userId, contentType, contentId);
                return true; // 已收藏，返回成功
            }
            
            // 创建收藏记录
            UserFavorite favorite = new UserFavorite();
            favorite.setUserId(userId);
            favorite.setContentType(contentType);
            favorite.setContentId(contentId);
            favorite.setTitle(title);
            favorite.setDescription(content);
            favorite.setImageUrl(imageUrl);
            favorite.setContentData(contentData);
            favorite.setCreateTime(LocalDateTime.now());
            favorite.setUpdateTime(LocalDateTime.now());
            favorite.setIsDeleted(false);
            
            int result = userFavoriteMapper.insert(favorite);
            log.info("Added to favorites: userId={}, type={}, id={}, title={}, result={}", 
                    userId, contentType, contentId, title, result);
            return result > 0;
        } catch (Exception e) {
            log.error("Error adding to favorites: userId={}, type={}, id={}", userId, contentType, contentId, e);
            return false;
        }
    }
    
    @Override
    public boolean removeFromFavorites(Long userId, Long favoriteId) {
        try {
            // 检查收藏是否存在且属于当前用户
            UserFavorite favorite = userFavoriteMapper.selectById(favoriteId);
            if (favorite == null || !userId.equals(favorite.getUserId())) {
                log.warn("Favorite not found or access denied: userId={}, favoriteId={}", userId, favoriteId);
                return false;
            }
            
            // 逻辑删除
            int result = userFavoriteMapper.deleteById(favoriteId);
            log.info("Removed from favorites: userId={}, favoriteId={}, result={}", userId, favoriteId, result);
            return result > 0;
        } catch (Exception e) {
            log.error("Error removing from favorites: userId={}, favoriteId={}", userId, favoriteId, e);
            return false;
        }
    }
    
    @Override
    public boolean removeFromFavoritesByContent(Long userId, String contentType, String contentId) {
        try {
            // 查找收藏记录
            UserFavorite favorite = userFavoriteMapper.selectByUserAndContent(userId, contentType, contentId);
            if (favorite == null) {
                log.warn("Favorite not found: userId={}, contentType={}, contentId={}", userId, contentType, contentId);
                return false;
            }
            
            // 逻辑删除
            int result = userFavoriteMapper.deleteById(favorite.getId());
            log.info("Removed from favorites by content: userId={}, contentType={}, contentId={}, result={}", 
                    userId, contentType, contentId, result);
            return result > 0;
        } catch (Exception e) {
            log.error("Error removing from favorites by content: userId={}, contentType={}, contentId={}", 
                    userId, contentType, contentId, e);
            return false;
        }
    }
    
    @Override
    public PageResult<UserTask> getUserTasks(Long userId, Integer status, Long current, Long size) {
        // Mock data - replace with actual database queries
        List<UserTask> tasks = new ArrayList<>();
        
        for (int i = 1; i <= 5; i++) {
            UserTask task = new UserTask();
            task.setId((long) i);
            task.setUserId(userId);
            task.setTaskType("daily");
            task.setTaskTitle("Daily check-in");
            task.setTaskDescription("Complete daily check-in to earn points");
            task.setTaskContent("points");
            task.setProgress(10);
            task.setTaskStatus(i % 2);
            task.setCreateTime(LocalDateTime.now().minusDays(i));
            tasks.add(task);
        }
        
        return new PageResult<>(200, "Success", tasks, 20L, 4L, false, true,
                               current.intValue(), size.intValue());
    }
    
    @Override
    public boolean completeUserTask(Long userId, Long taskId) {
        // Mock implementation - replace with actual database operation
        log.info("Completing task: userId={}, taskId={}", userId, taskId);
        return true;
    }
    
    @Override
    public BigDecimal getWalletBalance(Long userId) {
        // Mock data - replace with actual database query
        return new BigDecimal("98.50");
    }
    
    @Override
    public PageResult<WalletTransaction> getWalletTransactions(Long userId, Long current, Long size) {
        // Mock data - replace with actual database queries
        List<WalletTransaction> transactions = new ArrayList<>();
        
        for (int i = 1; i <= 8; i++) {
            WalletTransaction transaction = new WalletTransaction();
            transaction.setId((long) i);
            transaction.setUserId(userId);
            transaction.setTransactionType(i % 2 == 0 ? 1 : 2); // 1=income, 2=expense
            transaction.setAmount(new BigDecimal(i * 10));
            transaction.setDescription("Transaction " + i);
            transaction.setCreateTime(LocalDateTime.now().minusDays(i));
            transactions.add(transaction);
        }
        
        return new PageResult<>(200, "Success", transactions, 30L, 4L, false, true,
                               current.intValue(), size.intValue());
    }
    
    /**
     * 将UserFavorite对象转换为Map
     */
    private Map<String, Object> convertFavoriteToMap(UserFavorite favorite) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", favorite.getId());
        map.put("type", favorite.getContentType());
        map.put("contentId", favorite.getContentId());
        map.put("title", favorite.getTitle());
        map.put("content", favorite.getDescription());
        map.put("description", favorite.getDescription());
        map.put("imageUrl", favorite.getImageUrl());
        map.put("contentData", favorite.getContentData());
        map.put("createTime", favorite.getCreateTime());
        map.put("updateTime", favorite.getUpdateTime());
        return map;
    }
}